<?php
/**
 * app端 客户售后管理
 * Author: lyun
 * Date: 2018/12/12
 * Created by Panxsoft.
 */


namespace App\Http\Controllers\Api\V1\App\Order;

use App\Http\Controllers\ApiController;
use App\Http\Requests\Order\ReturnProductCancelRequest;
use App\Http\Requests\Order\ReturnProductIndexRequest;
use App\Http\Requests\Order\ReturnProductStoreRequest;
use App\Http\Services\Api\V1\App\Product\AfterSaleService;
use App\Models\Customers\Customer;
use App\Services\MobileApp\AppEnv;
use App\Services\Utils\Guard;
use Illuminate\Http\Request;

class AfterSaleController extends ApiController
{
    private $afterSaleService;

    public function __construct()
    {
        $this->afterSaleService = new AfterSaleService;
    }

    /**
     * @param ReturnProductIndexRequest $request
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function index(ReturnProductIndexRequest $request)
    {
        /** @var Customer $customer */
        $customer = Guard::customer();

        $returns = $this->afterSaleService->getReturnData($request, $customer);

        return $this->response(compact('returns'));
    }

    /**
     *  app端 售后数据的返回
     *
     * @return array|\Illuminate\Http\Response
     */
    public function create()
    {
        $return_reason = $this->afterSaleService->getReturnReason();
        $return_type = $this->afterSaleService->getReturnAction();
        $return_status = $this->afterSaleService->getReturnStatus();

        return $this->response(compact('return_reason', 'return_type', 'return_status'));
    }

    /**
     * app端 客户提交售后申请
     *
     * @param ReturnProductStoreRequest $request
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function store(ReturnProductStoreRequest $request)
    {
        /** @var Customer $customer */
        $customer = Guard::customer();
        $currency = AppEnv::currency();

        $return_data = $this->afterSaleService->assembleReturnData($request, $customer);

        $stored = $this->afterSaleService->storeReturnData($return_data);

        $stored->load('orderProducts', 'order', 'returnStatus', 'returnReason', 'returnHistories.returnStatus');

        $return_product_detail = $this->afterSaleService->assembleReturnProductData($stored, $currency, $customer->store_id);

        return $this->response(compact('stored', 'return_product_detail'));
    }

    /**
     * @deprecated (暂时不用)
     *  app端 取消售后申请
     *
     * @param ReturnProductCancelRequest $request
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function cancelReturnProduct(ReturnProductCancelRequest $request)
    {
        $return_id = $request->return_id;

        $updated = $this->afterSaleService->cancelReturnProduct($return_id);

        return $this->response(compact('updated'));
    }
}
